export { cookie } from './storage/cookie'
export { localStore } from './storage/localStore'
export { sessionStore } from './storage/sessionStore'
export { env } from './env'
export { header } from './header'
export { log } from './log'
export { confirm, alert } from '../utils/message'
export { token } from './token'
export { validator } from './validator'
export { default as _ } from 'lodash'
export { export2Excel } from './excel'
import { v4 as uuidv4 } from 'uuid'
import dayjs from 'dayjs'

// const { export2Excel } = import.meta.glob('./excel')
const customCache = new Set()

export const heightWidth = {
  headerHeight: 50,
  tagsHeight: 34,
  asideWidth: 210,
  asideWidthSmall: 64,
  contentTop: 15,
  contentRight: 15,
  contentBottom: 5,
  contentLeft: 15
}

export const util = {
  // export2Excel: export2Excel,

  /**
   * 生成uuid
   * @returns
   */
  uuid(): string {
    return uuidv4()
  },

  /**
   * 数字转换成英文字母
   * @param num
   * @returns
   */
  num2col(num: number): string {
    return String.fromCharCode(64 + num)
  },

  /**
   * 获取App高度
   * @returns
   */
  getAppHeight(): number {
    return document.documentElement.clientHeight
  },

  getTagsHeight(): number {
    return import.meta.env.VITE_APP_TAGS == '1' ? heightWidth.tagsHeight : 0
  },

  /**
   * 获取Content高度
   * @returns
   */
  getContentHeight(): number {
    return util.getAppHeight() - heightWidth.headerHeight - util.getTagsHeight()
  },

  /**
   * 获取Content宽度
   * @returns
   */
  getContentWidth(store?: any): number {
    return (
      document.documentElement.clientWidth -
      (store && !store.state.app.aside.opened ? heightWidth.asideWidthSmall : heightWidth.asideWidth)
    )
  },

  /**
   * 获取当前基础地址
   * @returns
   */
  getBaseUrl(): string {
    return `${window.location.protocol}//${window.location.host}`
  },

  /**
   * 获取api服务地址
   * @returns
   */
  getServerUrl(): string {
    const apiDomain = import.meta.env.VITE_API_DOMAIN
    if (/^(http|https):\/\//i.test(apiDomain)) {
      return apiDomain
    } else {
      return `${window.location.protocol}//${window.location.host}${apiDomain}`
    }
  },

  /**
   * 深度克隆对象
   * @param obj
   * @returns
   */
  cloneObject(obj: any) {
    return JSON.parse(JSON.stringify(obj))
  },

  /**
   * 向上递归所有父级
   * @param tree 数据数组
   * @param func 满足条件的函数
   * @param label 输出的值标签
   * @param path 输入集合
   * @returns
   */
  treeFindParent(tree: any[], func: (data: any) => boolean, label: string, path: any[] = []) {
    if (!tree) return []
    for (const data of tree) {
      // 这里按照你的需求来存放最后返回的内容吧
      path.push(data[label])
      if (func(data)) return path
      if (data.children) {
        const findChildren: any[] = util.treeFindParent(data.children, func, label, path)
        if (findChildren.length) return findChildren
      }
      path.pop()
    }
    return []
  },

  /**
   * 移动版模式
   * @returns
   */
  isMobile() {
    const WIDTH = 992 // refer to Bootstrap's responsive design
    const rect = document.body.getBoundingClientRect()
    return rect.width - 1 < WIDTH
  },

  isValidCustomScriptUrl(scriptUrl: string) {
    return scriptUrl && !customCache.has(scriptUrl)
  },

  createScriptUrlElement(scriptUrl: string) {
    if (util.isValidCustomScriptUrl(scriptUrl)) {
      const script = document.createElement('script')
      script.setAttribute('src', scriptUrl)
      script.setAttribute('data-namespace', scriptUrl)

      customCache.add(scriptUrl)
      document.body.appendChild(script)
    }
  },

  /**
   * 判断JSON是否空
   * @param obj
   * @returns
   */
  isEmptyObject(obj: any) {
    return JSON.stringify(obj) === '{}'
  },

  /**
   * 对象数组合并去重
   *
   * @export
   * @param {*} arr
   * @returns
   */
  concatUnique(arr1: any[], arr2: any[], key: any) {
    const arr = arr1.concat(arr2)
    const res = new Map()
    return arr.filter(item => !res.has(item[key]) && res.set(item[key], 1))
  },

  /**
   * 格式化时间成文本形式: 刚刚(0-15m), 15分钟前(15m-30m), 半小时前(30m-60m), 1小时前(60-120m), 今天 hh:mm, 昨天 hh:mm, MM-DD HH:MM
   * @param dataTime
   */
  formatTimeText(dateTime: string) {
    if (dateTime) {
      const diff = dayjs().diff(dateTime, 'minute')
      if (diff < 15) {
        return '刚刚'
      } else if (diff < 30) {
        return '15分钟之前'
      } else if (diff < 60) {
        return '半小时之前'
      } else if (diff < 120) {
        return '1小时之前'
      } else {
        const today = dayjs().format('YYYY-MM-DD')
        const day = dayjs(dateTime).format('YYYY-MM-DD')
        if (today === day) {
          return `今天 ${dayjs(dateTime).format('HH:MM')}`
        } else if (dayjs(day).add(1, 'day').format('YYYY-MM-DD') === today) {
          return `昨天 ${dayjs(dateTime).format('HH:MM')}`
        } else {
          const diffYear = dayjs().diff(dayjs(dateTime).format('YYYY-MM-DD'), 'year')
          if (diffYear === 0) {
            return dayjs(dateTime).format('M月D日 HH:MM')
          } else {
            return dayjs(dateTime).format('YYYY-MM-DD HH:MM')
          }
        }
      }
    } else {
      return dateTime
    }
  },

  randomInt(min: number, max: number): number {
    return Math.round(Math.random() * (max - min) + min)
  },

  /**
   * 生成随机字符
   * @param length 长度
   */
  randomStr(length: number): string {
    const pasArr = [
      // eslint-disable-next-line prettier/prettier
      'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
      // eslint-disable-next-line prettier/prettier
      'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
      // eslint-disable-next-line prettier/prettier
      '0','1','2','3','4','5','6','7','8','9',
      // eslint-disable-next-line prettier/prettier
      '_','-','$','%','&','@','+','!','.']

    let str = ''
    for (let i = 0; i < length; i++) {
      const index = Math.floor(Math.random() * pasArr.length)
      str += pasArr[index]
    }
    return str
  },

  randomWord(length: number): string {
    let code = ''
    for (let i = 0; i < length; i++) {
      const type = util.randomInt(1, 3)
      switch (type) {
        case 1:
          code += String.fromCharCode(util.randomInt(48, 57)) // 数字
          break
        case 2:
          code += String.fromCharCode(util.randomInt(65, 90)) // 大写字母
          break
        case 3:
          code += String.fromCharCode(util.randomInt(97, 122)) // 小写字母
          break
      }
    }
    return code
  },

  imgSuffix(): string[] {
    return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'ai', 'cdr', 'eps']
  },

  getSearch() {
    let search = window.location.search
    if (search) {
      const searchMap = {} as any
      if (search.startsWith('?')) {
        search = search.substring(1)
      }
      const params = search.split('&')
      params.forEach(p => {
        const index = p.indexOf('=')
        const key = p.substring(0, index)
        const val = p.substring(index + 1)
        searchMap[key] = val
      })
      return searchMap
    } else {
      return undefined
    }
  },
  getSSORedirectUri() {
    let redirectUri = import.meta.env.VITE_TAFFE_AUTH_REDIRECT_URI
    if (!redirectUri) {
      // 如果为空，取当前运行地址
      redirectUri = window.location.origin
    } else if (!redirectUri.startsWith('http')) {
      // 如果不为空，但是不是http开头，则加上当前运行地址
      redirectUri = `${window.location.origin}${redirectUri}`
    }
    return redirectUri
  }
}
